<template>
  <div>
    <nut-tabs background="#fff" type="smile" swipeable v-model="currentMenu">
      <nut-tab-pane v-for="(type, index) in evaluationType" :key="index"
        :customStyle="{ background: colors.bgColor, padding: ' 0' }" :title="type.label">
        <div v-if="isShow">
          <!-- 待评价 -->
          <div v-if="currentMenu == 0" bg-white p-24rpx mb-20rpx v-for="(item, i) in currentData.list" :key="i">
            <order rate :rateValue="evaluationData.rate" @onRate="onRate($event, i)" :res="item">
              <template #body="{ index }">
                <div mt-20rpx flex flex-a-c justify-end>
                  <nut-button customStyle="{width:'200rpx'}" size="small" @click.stop="talkCommont(item, index)" plain
                    type="primary">发表评价</nut-button>
                </div>
              </template>
            </order>
          </div>
          <!-- 已评价 -->
          <div v-if="currentMenu == 1" mb-20rpx v-for="(item, i) in currentData.list" :key="i">
            <div bg-white p-24rpx>
              <order :res="item">
                <template #footer>
                  <div pt-24rpx>
                    {{ item.content }}
                  </div>
                  <div flex flex-a-c justify-end>
                    <nut-button
                      @click="$navigateTo(`/pages/mine/evaluation/detail?data=${encodeURIComponent(JSON.stringify(item))}`)"
                      customStyle="{width:'200rpx'}" plain size="small" type="primary">评价详情</nut-button>
                  </div>
                </template>
              </order>
            </div>
          </div>

          <div v-if="!currentData.list.length" mt-100rpx>
            <empty />
          </div>
        </div>
      </nut-tab-pane>
    </nut-tabs>
    <nut-popup closeable round position="bottom" :custom-style="{ height: 700 + 'rpx' }"
      v-model:visible="showEvaluation">
      <div text-center px-20rpx>
        <div text-40rpx font-bold text-center h-160rpx line-height-160rpx>
          {{ evaluationData.content }} <span text-main-color font-bold>{{ evaluationData.grade === 'WORSE' ? '差评' :
      evaluationData.grade ===
        'MODERATE' ? '中评' : '好评' }}</span>
        </div>
        <div>
          <nut-rate allow-half v-model="evaluationData.rate" />
        </div>
        <div my-20rpx py-50rpx>
          <div text-main-color>
            期待您写出更多真实有帮助的评价
          </div>
          <div text-dark-color my-20rpx font-24rpx>
            您的评价对其他买家非常重要
          </div>
        </div>
        <div>
          <nut-button block type="primary" @click="talkCommont(currentData.data, currentData.index)">展开讲讲</nut-button>
          <div mt-30rpx></div>
          <nut-button block type="default" @click="reviews()" :loading="loading">直接提交</nut-button>
        </div>
      </div>
    </nut-popup>

  </div>
</template>

<script setup lang="ts">
import { evaluation, getComments, getOrderList } from '@/api/order';
import order from '@/components/basic-template/order.vue';
import empty from '@/components/empty/index.vue';
import { colors } from '@/constants/injection-key';
import { onPullDownRefresh, onReachBottom, onShow } from '@dcloudio/uni-app';
import type { Search } from '~/constants/types';
const isShow = ref<boolean>(false)
const showEvaluation = ref<boolean>(false)
const loading = ref<boolean>(false)
const evaluationData = ref<any>({
  rate: 0,
  content: "",
  grade: "",
  orderItemSn: "",
  skuId: "",
  descriptionScore: 0,
  serviceScore: 0,
  deliveryScore: 0,
  goodsId: ""
})
const evaluationType = ref<any>([
  {
    label: "待评价",
  },
  {
    label: "已评价",
  },
])
const system = ref<any>('')
const currentMenu = ref<number>(0)
watch(() => currentMenu.value, (val, oldVal) => {
  init()
})
watch(() => evaluationData.value.rate, (val, oldVal) => {
  if (val) {
    if (evaluationData.value.rate < 2) {
      evaluationData.value.grade = "WORSE"
    }
    if (evaluationData.value.rate >= 2 && evaluationData.value.rate < 4) {
      evaluationData.value.grade = "MODERATE"
    }
    if (evaluationData.value.rate >= 4) {
      evaluationData.value.grade = "GOOD"
    }
  }
}, { deep: true })
const currentData = ref<any>({
  list: [],
  data: "",
})

const searchForm = ref<Search>({
  pageNumber: 1,
  pageSize: 20,
  commentStatus: "UNFINISHED"
})

async function reviews() {
  loading.value = true
  const submit = { ...evaluationData.value }
  submit.serviceScore = submit.rate
  submit.descriptionScore = submit.rate
  submit.deliveryScore = submit.rate
  submit.content = submit.content + (submit.grade === 'WORSE' ? '差评' : submit.grade === 'MODERATE' ? '中评' : '好评')
  delete submit.rate
  const res = await evaluation(submit)
  loading.value = false
  showEvaluation.value = false
  if (res.data.success) {
    uni.showToast({
      title: "评论成功!",
      icon: "none"
    })
    init()
  }
}

// 发表评价
function talkCommont(item: any, index: number) {
  let skuId = item.orderItems[index].skuId;
  uni.navigateTo({
    url: `/pages/mine/evaluation/operation?sn=${item.orderItems[index].sn}&orderSn=${item.sn}&skuId=${skuId}`
  })
}

// 评价
function onRate(callback: { rate: number, [key: string]: any }, index: number) {
  console.log(callback, 'back')
  evaluationData.value.orderItemSn = callback.orderItems[callback._index].sn
  evaluationData.value.skuId = callback.orderItems[callback._index].skuId
  evaluationData.value.rate = callback.rate
  evaluationData.value.goodsId = callback.orderItems[callback._index].goodsId

  currentData.value.data = callback
  currentData.value.index = index
  evaluationData.value.content = "商品综合评价"
  showEvaluation.value = true
}

async function init() {
  isShow.value = false
  currentData.value.list = []
  currentData.value.pageNumber = 1
  await fetch()

}
// 获取优惠券
async function fetch() {
  uni.stopPullDownRefresh();
  let res
  if (currentMenu.value == 1) {
    res = await getComments(searchForm.value)
  }
  else {
    res = await getOrderList(searchForm.value)
  }
  isShow.value = true
  if (res.data.success) {
    currentData.value.data = res.data.result
    res.data.result.records.forEach((item: any) => {
      if (item.orderItems) {
        item.orderItems.length ? item.orderItems.forEach((order: any) => {
          order.thumbnail = order.image
        }) : '';
        item.orderItems.rate = 0;
      }
      else {
        item.thumbnail = item.goodsImage;
        item.rate = 0;
      }
    })
    currentData.value.list.push(...res.data.result.records)
    // console.log(currentData.value)
  }
}

onPullDownRefresh(() => {
  init()
})
onReachBottom(() => {
  if (currentData.value.data?.total > currentData.value.pageNumber * currentData.value.pageSize) {
    currentData.value.pageNumber++;
    fetch()
  }
})

onShow(async () => {
  currentData.value.pageNumber = 1
  init();
  system.value = await uni.getSystemInfo();
  showEvaluation.value = false;
})
</script>

<style scoped></style>
